package com.zzzy.config;


import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Component
@Aspect
@Order(-1)
public class DynamicDataSourceAspect {

    private Logger logger = Logger.getLogger(this.getClass());

    //改变数据源
    @Before("@annotation(DataSource)")
    public void changeDataSource(JoinPoint joinPoint) {

        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        Object tenent = request.getSession().getAttribute("tenent");

        String dbid = tenent.toString();

        logger.debug("使用数据源：" + dbid);
        DynamicDataSourceContextHolder.setDataSource(dbid);

    }

    @After("@annotation(DataSource)")
    public void clearDataSource(JoinPoint joinPoint) {
        logger.debug("清除数据源：" + DynamicDataSourceContextHolder.getDataSource());
        DynamicDataSourceContextHolder.clearDataSource();
    }
}

